package com.yft.data.interceptor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Repository
public class LoggerInterceptor extends HandlerInterceptorAdapter {
	private static final Logger logger = Logger
			.getLogger(LoggerInterceptor.class);
	private static final String noFilterUri = "background/";
	// 后台session控制
	private static final String[] noFiltersPage = new String[] { "login.html",
			"veriCode.html", "index.html", "logout.html" };

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		String uri = request.getRequestURI();
		// 这个拦截器的排除uri
		if (uri.indexOf(noFilterUri) == -1) {
			boolean beFilter = true;
			for (String s : noFiltersPage) {
				// 如果包含不用过滤的地址
				if (uri.indexOf(s) != -1) {
					beFilter = false;
					break;
				}
			}
			// 如果不在filter列表里
			if (beFilter) {
				// System.out.println("LoggerInterceptor");
				Map paramsMap = request.getParameterMap();
				Map<Object, Object> valuemap = new HashMap<Object, Object>();
				String params = null;
				for (Iterator<Map.Entry> it = paramsMap.entrySet().iterator(); it
						.hasNext();) {
					Map.Entry entry = it.next();
					Object[] values = (Object[]) entry.getValue();
					// System.out.println(entry.getKey()+"-"+values[0]);
					if (values[0] != null) {
						String value = new String(values[0].toString().trim()
								.getBytes("ISO-8859-1"), "utf-8");
						valuemap.put(entry.getKey(), value);
						//System.out.println(entry.getKey()+"-"+value);
					} else {
						valuemap.put(entry.getKey(), values[0]);
					}
				}
				ObjectMapper objectMapper = new ObjectMapper();
				try {   
					params = objectMapper.writeValueAsString(valuemap);
				} catch (JsonGenerationException e) {
					logger.error(e.getMessage());
				} catch (JsonMappingException e) {
					logger.error(e.getMessage());
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
				MDC.put("pathinfo", uri);
				// System.out.println(params);
				logger.info(params);
			}
		}
		return super.preHandle(request, response, handler);
	}

}
